var ctx;
var level = -1;

function setCtx(ctx){
	this.ctx = ctx;
	
}

$(function(){
    initListener();
    var level = $("#editLevel").children('option:selected').val();
    if(level > -1) {
        $("#editLevel").trigger('change');
    }
})
function ifNull(mess){
	if(mess == null || mess == undefined){
		mess = "";
	}
	return mess;
}

//var dLevel = $("#level").val();
//if(dLevel > 1 ){
//	$("#parentCategory").show();
//}else{
//	$("#parentCategory").hide();
//}


//编辑或新增区域等级下拉框
function initListener(){
	$('#editLevel').change(function(){ 
		
		level = $(this).children('option:selected').val();
		
		if(level == 1){
//			$("#parentCategory").hide();
			parentList(0);
		}else if(level == 2){
//			$("#parentCategory").show();
			parentList(1);
		}else{
//			$("#parentCategory").hide();
		}
	});
}

//取上一级的集合
function parentList(level){
	var url;
	if(0 == level) {
		url = ctx+"/goodsCategory/shopCategoryByLevel";
	} else {
		url = ctx+"/goodsCategory/goodsCategoryByLevel";
	}
	$.post(url, {level:level},
		function(data){
			data = JSON.parse(data);
			var parentId = $("#parentId");
			parentId.empty();
			for(var i=0;i<data.length;i++) {
				var parent = data[i];
				parentId.append("<option value="+ parent.id+">"+ parent.name+"</option>"); 
		}
	});
}

//新增或编辑菜单(1:新增 2:编辑)
function saveOrUpdateCategory (){
	var id = 0;
	var parentId = 0;

	if($("#categoryId").val() != null && $("#categoryId").val() != ""){
		id = $("#categoryId").val();
	}
	
	if($("#editLevel").val() == 1){
		parentId = 0;
	}else{
		parentId = $("#parentId").val();
	}
	
	save(id,parentId);
}

var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
function save(id,parentId){
	if(level == -1){
		level = $("#level").val();
	}
	var distribute = $("input:radio[name=distribute]:checked").val();
	var servicePrice = $("input:radio[name=servicePrice]:checked").val();
	var confirm = $("input:radio[name=confirm]:checked").val();
	var name = $("#name").val();
	var descrip = $("#descrip").val();
	//解决ie9以下placeholder与value重复的问题
	if(name == $("#name").attr("placeholder")){
		name = "";
	}
	//解决ie9以下placeholder与value重复的问题
	if(descrip == $("#descrip").attr("placeholder")){
		descrip = "";
	}

	var index1 = layer.load(1);
			$.post(ctx+"/goodsCategory/saveOrUpdateGoodsCategory",{
				name : name,
				descrip : descrip,
				level:level,
				pid : parentId,
				id:id,
				distribute : distribute,
				servicePrice : servicePrice,
				confirm : confirm
					},function(data){
						data = JSON.parse(data);
						if(data.success){
							layer.msg("操作成功",{
							    icon: 1,
							    time: 1000 //2秒关闭（如果不配置，默认是3秒）
							},function(){
								parent.loadContent("/goodsCategory/categoryList");
								parent.layer.close(index); //根据窗口索引关闭窗口   
							});
						} else {
							layer.close(index1);
							layer.msg(data.msg,{
							    icon: 2,
							    time: 1000 //2秒关闭（如果不配置，默认是3秒）
							});
						}
					});
			
	
}
 